package cn.kgc.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.kgc.pojo.Resume;
import cn.kgc.service.resumeService;
import cn.kgc.until.NiuUntil;
import cn.kgc.until.QiNiuYunUntil;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author: 申乾航
 * @date: 2022/2/28
 * @description:
 */

@RequestMapping("/resumes")
@Controller
public class resumeControllers {


    @Resource
    private resumeService resumeServices;


    @PostMapping("/image")
    @ResponseBody
    public String postUpload(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile, HttpServletResponse response,@RequestParam ("posCode") String posCode, Resume resume) throws IOException {

        // 用来获取其他参数
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        //String name = params.getParameter("username");
        if (!multipartFile.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();


            String filename=multipartFile.getOriginalFilename();
            System.out.println("========-----ssssss"+filename);

          //  System.out.println("+++++"+inputStream);
            // 生成新文件名
          //  String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
          //  System.out.println("+++++-----"+newFileName);
            //获取文件类型
            String contentType = multipartFile.getContentType();

            System.out.println("-=-=-=-=-=-=--=-="+contentType);

            //前缀
            boolean isPre = contentType.startsWith("image");
            System.out.println("是否是图片："+isPre);

            String path = NiuUntil.uploadQNFile(inputStream, filename);

            System.out.println("-================="+path);

            System.out.println("图片大小（字节）：" + multipartFile.getSize());

            System.out.println("七牛云返回的图片链接:" + path);

            resume.setAffix(path);
            Integer postions = resumeServices.selId(posCode);
            resume.setPosId(postions);
            boolean tianjia = resumeServices.tianjia(resume);
            if(tianjia){
                System.out.println("成功");

            }else {
                System.out.println("失败");
            }

            return path;
        }
        return "上传失败";
    }



    @PostMapping("/xiugai")
    @ResponseBody
    public String postUpload12(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile, HttpServletResponse response,@RequestParam ("posCode") String posCode, Resume resume) throws IOException {

        // 用来获取其他参数
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        //String name = params.getParameter("username");
        if (!multipartFile.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) multipartFile.getInputStream();


            String filename=multipartFile.getOriginalFilename();
            System.out.println("========-----ssssss"+filename);

            //  System.out.println("+++++"+inputStream);
            // 生成新文件名
            //  String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            //  System.out.println("+++++-----"+newFileName);
            //获取文件类型
            String contentType = multipartFile.getContentType();

            System.out.println("-=-=-=-=-=-=--=-="+contentType);

            //前缀
            boolean isPre = contentType.startsWith("image");
            System.out.println("是否是图片："+isPre);

            String path = NiuUntil.uploadQNFile(inputStream, filename);

            System.out.println("-================="+path);

            System.out.println("图片大小（字节）：" + multipartFile.getSize());

            System.out.println("七牛云返回的图片链接:" + path);

            resume.setAffix(path);
            Integer postions = resumeServices.selId(posCode);
            resume.setPosId(postions);
            boolean tianjia = resumeServices.xiugai_shen(resume);
            if(tianjia){
                System.out.println("成功");

            }else {
                System.out.println("失败");
            }

            return path;
        }
        return "上传失败";
    }


    /**
     * 七牛云下载
     * String fileName,
     */
    @RequestMapping("/downloads")
    public  void download(@RequestParam("id") Integer id, HttpServletResponse response) throws IOException {
       // String domainOfBucket =QiNiuYunUntil.DOMAIN ;

        Resume resume = resumeServices.chakan(id);
        String pa=resume.getAffix();

        File dateDir = new File("D://七牛云");
        String[] s = dateDir.list();
        int num=s.length;
        System.out.println("第一次的文件夹文件的数量============"+num);

        String encodedFileName = null;
        //encodedFileName = URLEncoder.encode(resume.getAffix(), "utf-8");
        response.setHeader("content-disposition", "inline;fileName=" + pa);


        System.out.println("================"+encodedFileName);
        //  String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

        Auth auth = Auth.create(QiNiuYunUntil.AK, QiNiuYunUntil.SK);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(pa, expireInSeconds);
        System.out.println(finalUrl);

        if (!dateDir.exists()) {
            dateDir.mkdirs();    // mkdirs()可以创建多级目录
        }
        HttpUtil.downloadFile(finalUrl, FileUtil.file("D://七牛云"));
        String[] ss = dateDir.list();
        int nums=ss.length;
        System.out.println("第二次的文件夹文件的数量===========-------====="+nums);
        response.setCharacterEncoding("UTF-8");
        if (nums>num){
            response.getWriter().print("<script>alert('文件已下载成功，请到指定路径下预览！！！');window.location.href='/resume/h4';</script>");
            System.out.println("文件已下载成功，请到指定路径下预览");
        }else{
             response.getWriter().print("<script>alert('文件夹已有或文件已更新为新！！！');window.location.href='/resume/h4';</script>");
            System.out.println("文件夹已有或文件已更新为新");
        }
    }
}
